package com.example.demos.web.controller;

import com.example.demos.dto.GoodsAddDTO;
import com.example.demos.dto.GoodsQueryParamDTO;
import com.example.demos.entity.Goods;
import com.example.demos.entity.GoodsType;
import com.example.demos.service.GoodsService;
import com.example.demos.util.PageBean;
import com.example.demos.util.Result;
import com.example.demos.util.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import static com.example.demos.util.ResultEnum.INTERNAL_SERVER_ERROR;

@RestController
@RequestMapping("/v2/")
public class GoodController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("goods/listByPage")
    public Result<?> listByPage(GoodsQueryParamDTO goodsQueryParamDTO) {
        return Result.ok(goodsService.goodsListByPage(goodsQueryParamDTO));
    }

    @GetMapping("goods/goodstypelist")
    public Result<PageBean<List<GoodsType>>> goodsTypeList() {
        return Result.ok(goodsService.getGoodsType());
    }

    @PostMapping("goods/add")
    public Result<Void> addGoods(GoodsAddDTO goodsAddDTO) {
        int i = goodsService.addGoods(goodsAddDTO);
        if (i == 1) {
            return Result.err(400, "商品字段填写不完整或金额不合法");
        } else if (i == 2) {
            return Result.err(400, "该商品和类型已存在");
        } else if (i == 3) {
            return Result.ok("新增成功");
        } else {
            return Result.err(400, "失败，请联系管理员");
        }
    }

    @PostMapping("//goods/update")
    public Result<Void> updateGoods(BigInteger goodsType, String name, String origin, BigInteger uuid,
                                    String producer, String unit, BigDecimal inPrice,
                                    BigDecimal outPrice, HttpSession httpSession) {

        try {
            if (goodsService.updateGoods(goodsType, name, origin, producer, unit, inPrice, outPrice, uuid, httpSession)) {
                return Result.ok("修改成功");
            } else {
                return Result.err(400, "数据库错误");
            }
        } catch (Exception e) {
            return Result.err(400, "修改的商品类型名称不能与其它商品类型名称重复");
        }
    }

    @GetMapping("goods/selectone")
    public Result<?> selectOne(Integer id) {
        PageBean<Goods> goods = goodsService.selectOne(id);
        return goods != null ? Result.ok(goods) : Result.err(INTERNAL_SERVER_ERROR);
    }

    @DeleteMapping("goods")
    public Result<?> deleteGoods(Integer id) {
        return goodsService.deleteGoods(id) > 0
                ? Result.ok("删除成功")
                : goodsService.deleteGoods(id) == -1
                ? Result.bizErr("库存记录中还有这个商品")
                : Result.err(400, "删除失败");
    }


}
